import express, { Request, Response } from "express"
import { UserMangeContext } from "../../../../context/UserMangeContext"
import { UserListParam ,PutUserStateParam} from "@Tea/model"
import { checkError } from "../../../../utils/token"
import { catchError, useCheckAndResponse } from "../../../../utils/common"
import { UserState } from "../../../../dao/UserState"

const userList = express.Router()

userList.post("/userPageList", async (req: Request, res: Response) => {
  try {
    res.send({
      code: 1,
      msg: "查询成功",
      ...(await UserMangeContext.getInstance().getUserList(req.body as UserListParam, "user"))
    })
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})

userList.put("/putUserState", async (req: Request, res: Response) => {
  catchError(res,async () => {
    const params = req.body as PutUserStateParam
    const result = await UserMangeContext.getInstance().putUserState(params)
    const checkResult = useCheckAndResponse(res, result[0], params.enable === 1 ? "启用成功" : "停用成功")

    // 操作成功后，操作缓存数据
    if (checkResult) {
      UserState.getInstance()[params.enable === 1 ? "enable" : "deactivate"](params.userId)
    }
  })
})

export default userList